package test.algos.sorting.quicksort;

import java.util.List;

import test.algos.sorting.SortUtil;

public class Partitioner {

	private List<Integer> input;

	public Partitioner(List<Integer> input) {

		this.input = input;

	}

	public Integer partition(int pivotIndex) {

		pivotToFirst(pivotIndex);
		Integer pivotElem = input.get(0);

		int crossBoundary = 1;

		for (int elemIndex = 1; elemIndex < input.size(); elemIndex++) {

			Integer curElem = input.get(elemIndex);

			Integer compareValue = SortUtil
					.compareAndReturn(curElem, pivotElem);

			if (compareValue != null && compareValue < 0) {
				SortUtil.swap(elemIndex, crossBoundary, input);
				crossBoundary++;
			}
		}

		SortUtil.swap(0, crossBoundary - 1, input);

		return crossBoundary - 1;
	}

	private void pivotToFirst(int pivotIndex) {
		if (pivotIndex != 0) {
			SortUtil.swap(1, pivotIndex, input);
		}
	}

}
